<?php
/**
 * @author spenceryg
 * @date 2022/4/11
 * @time 11:57 上午
 * @focus love & life
 */


namespace app\wechat\service;


use app\wechat\model\WechatUser;

class WechatUserService
{
    /**
     * addUser
     * @param string $union_id
     */
    public static function addUser(string $union_id)
    {
        $add = [];
        $add['union_id'] = $union_id;
        WechatUser::create($add);

    }

    /**
     * findUserByUnionID
     * @param string $union_id
     * @return WechatUser|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function findUserByUnionID(string $union_id)
    {
        return WechatUser::where('union_id', $union_id)->find();
    }

    /**
     * login
     * @param string $union_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function login(string $union_id)
    {
        if (!self::findUserByUnionID($union_id)){
            self::addUser($union_id);
        }

        session('wechat_user', self::findUserByUnionID($union_id));
    }
}